package lex.util;

import java.awt.*;

public class Utilities {
	public final static String CLIP_STRING = "...";

	private Utilities() {
	}

	/**
	 * Clips the String to the space provided if it is too long.
	 * 
	 * @param fm
	 *            FontMetrics used to measure the String width
	 * @param string
	 *            String to possibly clip
	 * @param availWidth
	 *            Amount of space that the string can be drawn in
	 * @return Clipped string that can fit in the provided space.
	 */
	public static String clipStringIfNecessary(FontMetrics fm, String string, int availWidth) {
		if (string == null || string.length() == 0) {
			return "";
		}
		int stringWidth = fm.stringWidth(string);
		if (stringWidth > availWidth)
			return Utilities.clipString(fm, string, availWidth);
		return string;
	}

	/**
	 * Clips the String to the width provided.
	 * 
	 * NOTE: This assumes that the string doesn't fit in the available space.
	 * 
	 * @param fm
	 *            FontMetrics used to measure the String width
	 * @param string
	 *            String to display
	 * @param availWidth
	 *            Amount of space that the string can be drawn in
	 * @return Clipped string that can fit in the provided space.
	 */
	public static String clipString(FontMetrics fm, String string, int availWidth) {
		int clipWidth = fm.stringWidth(CLIP_STRING);
		int chars = 0;
		for (int maxLength = string.length(); chars < maxLength; chars++) {
			clipWidth += fm.charWidth(string.charAt(chars));
			if (clipWidth > availWidth) {
				break;
			}
		}
		string = string.substring(0, chars) + CLIP_STRING;
		return string;
	}

	public static void setMaximizeBounds(Frame frame) {
		if (frame.getMaximizedBounds() != null) {
			return;
		}
		Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration());
		Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
		// spare any Systemmenus or Taskbars or ??...
		int w = size.width - insets.left - insets.right;
		int h = size.height - insets.top - insets.bottom;
		Rectangle maxBounds = new Rectangle(insets.left, insets.top, w, h);
		frame.setMaximizedBounds(maxBounds);
	}
}
